import * as vscode from 'vscode';
import { chineseToEnglish } from './translations';
import { TranslationService } from './translationService';
import { UpdateService } from './updateService';

// 获取配置
function getConfig() {
    return vscode.workspace.getConfiguration('snakecasepro');
}

// 将中文转换为英文
async function translateChinese(text: string, targetCase: string = 'default'): Promise<string> {
    const config = getConfig();
    const apiKey = config.get<string>('apiKey', '');
    const aiModel = config.get<string>('aiModel', 'Qwen/Qwen2.5-7B-Instruct');
    const enableApiTranslation = config.get<boolean>('enableApiTranslation', true);
    const fallbackToLocal = config.get<boolean>('fallbackToLocal', true);

    try {
        // 如果启用API翻译且有API密钥，则尝试使用轨迹流动API
        if (enableApiTranslation && apiKey) {
            TranslationService.setApiKey(apiKey);
            TranslationService.setAiModel(aiModel);
            return await TranslationService.translate(text, targetCase);
        } else {
            // 如果启用了API翻译但没有密钥，显示设置提示
            if (enableApiTranslation && !apiKey) {
                const action = await vscode.window.showInformationMessage(
                    '🔑 检测到您尚未配置轨迹流动API密钥\n\n配置后可享受免费AI翻译，翻译质量更佳！',
                    '立即配置密钥',
                    '使用本地词典',
                    '了解如何获取密钥'
                );

                if (action === '立即配置密钥') {
                    vscode.commands.executeCommand('snakecasepro.setApiKey');
                    throw new Error('用户选择配置密钥，已打开设置界面');
                } else if (action === '了解如何获取密钥') {
                    vscode.env.openExternal(vscode.Uri.parse('https://siliconflow.cn'));
                    throw new Error('用户选择了解如何获取密钥');
                }
                // 如果选择"使用本地词典"，继续执行下面的本地翻译逻辑
            }

            // 直接使用本地词典翻译
            throw new Error('API翻译未启用或未配置密钥，使用本地词典');
        }
    } catch (error) {
        // 如果API调用失败且允许回退，使用本地词典翻译
        if (fallbackToLocal) {
            let result = text;
            const sortedWords = Object.keys(chineseToEnglish).sort((a, b) => b.length - a.length);

            for (const chinese of sortedWords) {
                const english = chineseToEnglish[chinese];
                const regex = new RegExp(chinese, 'g');
                result = result.replace(regex, english);
            }

            return result;
        } else {
            throw error;
        }
    }
}

// 工具函数：将文本转换为驼峰命名
async function toCamelCase(text: string): Promise<string> {
    // 先进行中文翻译
    const translatedText = await translateChinese(text, 'camelCase');
    // 如果API直接返回了正确格式，就直接使用，否则进行格式转换
    if (translatedText && /^[a-z][a-zA-Z0-9]*$/.test(translatedText)) {
        return translatedText;
    }
    return translatedText.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
}

// 工具函数：将文本转换为大驼峰命名
async function toPascalCase(text: string): Promise<string> {
    // 先进行中文翻译
    const translatedText = await translateChinese(text, 'PascalCase');
    // 如果API直接返回了正确格式，就直接使用，否则进行格式转换
    if (translatedText && /^[A-Z][a-zA-Z0-9]*$/.test(translatedText)) {
        return translatedText;
    }
    const camelCase = translatedText.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
}

// 工具函数：将文本转换为下划线命名
async function toSnakeCase(text: string): Promise<string> {
    // 先进行中文翻译
    const translatedText = await translateChinese(text, 'snake_case');
    // 如果API直接返回了正确格式，就直接使用，否则进行格式转换
    if (translatedText && /^[a-z][a-z0-9_]*$/.test(translatedText)) {
        return translatedText;
    }
    return translatedText
        .replace(/([A-Z])/g, '_$1')
        .toLowerCase()
        .replace(/^_/, '')
        .replace(/[-_\s]+/g, '_');
}

// 工具函数：将文本转换为短横线命名
async function toKebabCase(text: string): Promise<string> {
    // 先进行中文翻译
    const translatedText = await translateChinese(text, 'kebab-case');
    // 如果API直接返回了正确格式，就直接使用，否则进行格式转换
    if (translatedText && /^[a-z][a-z0-9-]*$/.test(translatedText)) {
        return translatedText;
    }
    return translatedText
        .replace(/([A-Z])/g, '-$1')
        .toLowerCase()
        .replace(/^_/, '')
        .replace(/[-_\s]+/g, '-');
}

// 获取选中的文本
function getSelectedText(editor: vscode.TextEditor): string {
    const selection = editor.selection;
    return editor.document.getText(selection);
}

// 替换选中的文本
function replaceSelectedText(editor: vscode.TextEditor, newText: string) {
    const selection = editor.selection;
    editor.edit(editBuilder => {
        editBuilder.replace(selection, newText);
    });
}

// 通用的转换函数，带加载提示
async function convertWithProgress(
    convertFn: (text: string) => Promise<string>,
    formatName: string,
    selectedText: string,
    editor: vscode.TextEditor
): Promise<void> {
    const config = getConfig();
    const apiKey = config.get<string>('apiKey', '');
    const enableApiTranslation = config.get<boolean>('enableApiTranslation', true);

    // 如果启用API翻译且有API密钥，显示进度条
    if (enableApiTranslation && apiKey) {
        await vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: `🚀 正在转换为${formatName}格式...`,
            cancellable: false
        }, async (progress) => {
            progress.report({ message: `正在翻译 "${selectedText}"` });

            try {
                const convertedText = await convertFn(selectedText);
                progress.report({ message: '翻译完成，正在替换文本...' });
                replaceSelectedText(editor, convertedText);

                // 显示成功消息
                vscode.window.showInformationMessage(
                    `✅ 转换成功: "${selectedText}" → "${convertedText}"`
                );
            } catch (error: any) {
                // 如果出错，显示错误信息
                vscode.window.showErrorMessage(`❌ 转换失败: ${error.message}`);
            }
        });
    } else {
        // 本地翻译，直接转换（通常很快）
        try {
            const convertedText = await convertFn(selectedText);
            replaceSelectedText(editor, convertedText);
            vscode.window.showInformationMessage(
                `✅ 转换成功: "${selectedText}" → "${convertedText}"`
            );
        } catch (error: any) {
            vscode.window.showErrorMessage(`❌ 转换失败: ${error.message}`);
        }
    }
}

export function activate(context: vscode.ExtensionContext) {
    // 插件激活时自动检查更新
    UpdateService.autoCheckUpdates();

    // 注册配置API密钥的命令（向后兼容）
    let setApiKeyCommand = vscode.commands.registerCommand('snakecasepro.setApiKey', async () => {
        // 首先显示说明和注册链接
        const setupAction = await vscode.window.showInformationMessage(
            '🚀 轨迹流动API配置指南\n\n' +
            '• 完全免费使用\n' +
            '• 支持多种AI模型\n' +
            '• 翻译质量优秀\n' +
            '• 1秒快速响应\n\n' +
            '需要先注册轨迹流动账号获取API密钥',
            '前往注册',
            '我已有密钥',
            '取消'
        );

        if (setupAction === '前往注册') {
            vscode.env.openExternal(vscode.Uri.parse('https://siliconflow.cn'));
            vscode.window.showInformationMessage('请在轨迹流动官网注册后，复制API密钥返回此处配置');
            return;
        } else if (setupAction === '取消') {
            return;
        }

        // 如果选择"我已有密钥"，显示输入框
        const apiKey = await vscode.window.showInputBox({
            prompt: '请输入您的轨迹流动API密钥',
            password: true,
            placeHolder: 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            validateInput: (value) => {
                if (!value || value.trim().length === 0) {
                    return '密钥不能为空';
                }
                if (!value.startsWith('sk-')) {
                    return '轨迹流动密钥通常以 sk- 开头';
                }
                return null;
            }
        });

        if (apiKey) {
            const config = getConfig();
            await config.update('apiKey', apiKey, vscode.ConfigurationTarget.Global);
            vscode.window.showInformationMessage(
                '✅ API密钥配置成功！现在您可以享受免费AI翻译服务了',
                '查看当前配置',
                '立即体验'
            ).then(action => {
                if (action === '查看当前配置') {
                    vscode.commands.executeCommand('snakecasepro.showConfig');
                } else if (action === '立即体验') {
                    vscode.window.showInformationMessage('请选中任意中文文本，然后使用快捷键或右键菜单进行转换！');
                }
            });
        }
    });

    // 注册设置AI模型的命令
    let setAiModelCommand = vscode.commands.registerCommand('snakecasepro.setAiModel', async () => {
        const currentModel = getConfig().get<string>('aiModel', 'Qwen/Qwen2.5-7B-Instruct');

        const modelName = await vscode.window.showInputBox({
            prompt: '请输入轨迹流动AI模型名称',
            value: currentModel,
            placeHolder: '例如: deepseek-ai/DeepSeek-V3',
            validateInput: (value) => {
                if (!value || value.trim().length === 0) {
                    return '模型名称不能为空';
                }
                return null;
            }
        });

        if (modelName && modelName.trim()) {
            const config = getConfig();
            await config.update('aiModel', modelName.trim(), vscode.ConfigurationTarget.Global);
            vscode.window.showInformationMessage(`AI模型已设置为: ${modelName.trim()}`);
        }
    });

    // 注册清除API密钥的命令
    let clearApiKeyCommand = vscode.commands.registerCommand('snakecasepro.clearApiKey', async () => {
        const config = getConfig();
        const currentApiKey = config.get<string>('apiKey', '');

        if (!currentApiKey) {
            vscode.window.showInformationMessage('当前未配置API密钥');
            return;
        }

        const confirm = await vscode.window.showWarningMessage(
            '⚠️ 确定要清除API密钥吗？\n\n清除后将无法使用AI翻译功能，只能使用本地词典翻译。',
            '确定清除',
            '取消'
        );

        if (confirm === '确定清除') {
            await config.update('apiKey', '', vscode.ConfigurationTarget.Global);
            vscode.window.showInformationMessage(
                '✅ API密钥已清除，现在将使用本地词典进行翻译',
                '重新配置密钥'
            ).then(action => {
                if (action === '重新配置密钥') {
                    vscode.commands.executeCommand('snakecasepro.setApiKey');
                }
            });
        }
    });

    // 注册打开设置的命令
    let openSettingsCommand = vscode.commands.registerCommand('snakecasepro.openSettings', () => {
        vscode.commands.executeCommand('workbench.action.openSettings', 'snakecasepro');
    });

    // 注册显示当前配置的命令
    let showConfigCommand = vscode.commands.registerCommand('snakecasepro.showConfig', () => {
        const config = getConfig();
        const apiKey = config.get<string>('apiKey', '');
        const aiModel = config.get<string>('aiModel', 'Qwen/Qwen2.5-7B-Instruct');
        const enableApiTranslation = config.get<boolean>('enableApiTranslation', true);
        const fallbackToLocal = config.get<boolean>('fallbackToLocal', true);

        const configInfo = [
            `🔑 API密钥: ${apiKey ? '已配置' : '未配置'}`,
            `🤖 AI模型: ${aiModel}`,
            `🌐 API翻译: ${enableApiTranslation ? '启用' : '禁用'}`,
            `📚 本地回退: ${fallbackToLocal ? '启用' : '禁用'}`
        ].join('\n');

        vscode.window.showInformationMessage(
            `GoodName 当前配置:\n${configInfo}`,
            '打开设置'
        ).then(selection => {
            if (selection === '打开设置') {
                vscode.commands.executeCommand('workbench.action.openSettings', 'snakecasepro');
            }
        });
    });

    // 注册转换为驼峰命名的命令
    let camelCaseCommand = vscode.commands.registerCommand('snakecasepro.convertToCamelCase', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const selectedText = getSelectedText(editor);
            if (selectedText) {
                await convertWithProgress(toCamelCase, '驼峰命名', selectedText, editor);
            } else {
                vscode.window.showWarningMessage('请先选中要转换的文本');
            }
        }
    });

    // 注册转换为大驼峰命名的命令
    let pascalCaseCommand = vscode.commands.registerCommand('snakecasepro.convertToPascalCase', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const selectedText = getSelectedText(editor);
            if (selectedText) {
                await convertWithProgress(toPascalCase, '大驼峰命名', selectedText, editor);
            } else {
                vscode.window.showWarningMessage('请先选中要转换的文本');
            }
        }
    });

    // 注册转换为下划线命名的命令
    let snakeCaseCommand = vscode.commands.registerCommand('snakecasepro.convertToSnakeCase', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const selectedText = getSelectedText(editor);
            if (selectedText) {
                await convertWithProgress(toSnakeCase, '下划线命名', selectedText, editor);
            } else {
                vscode.window.showWarningMessage('请先选中要转换的文本');
            }
        }
    });

    // 注册转换为短横线命名的命令
    let kebabCaseCommand = vscode.commands.registerCommand('snakecasepro.convertToKebabCase', async () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const selectedText = getSelectedText(editor);
            if (selectedText) {
                await convertWithProgress(toKebabCase, '短横线命名', selectedText, editor);
            } else {
                vscode.window.showWarningMessage('请先选中要转换的文本');
            }
        }
    });

    // 注册检查更新的命令
    let checkUpdateCommand = vscode.commands.registerCommand('snakecasepro.checkUpdate', async () => {
        await UpdateService.checkForUpdates(true);
    });

    // 注册查看公告的命令
    let showAnnouncementCommand = vscode.commands.registerCommand('snakecasepro.showAnnouncement', async () => {
        await UpdateService.showAnnouncement();
    });

    // 注册显示关于信息的命令
    let showAboutCommand = vscode.commands.registerCommand('snakecasepro.showAbout', async () => {
        const versionInfo = await UpdateService.getVersionInfo();
        const currentVersion = '0.0.3';

        let aboutMessage = `📱 GoodName - 免费AI翻译命名助手\n\n`;
        aboutMessage += `🔧 当前版本: v${currentVersion}\n`;
        aboutMessage += `🌐 开发者: IT工具开发团队\n`;
        aboutMessage += `💻 GitHub: https://github.com/your-repo\n\n`;
        aboutMessage += `🎯 功能特色:\n`;
        aboutMessage += `• 🆓 完全免费的AI翻译\n`;
        aboutMessage += `• ⚡ 1秒极速响应\n`;
        aboutMessage += `• 🤖 支持多种AI模型\n`;
        aboutMessage += `• 📚 本地词典备份\n\n`;

        if (versionInfo) {
            aboutMessage += `📢 最新版本: v${versionInfo.version.v}\n`;
            aboutMessage += `📝 更新说明: ${versionInfo.version.describe}`;
        }

        vscode.window.showInformationMessage(
            aboutMessage,
            '检查更新',
            '查看公告',
            '访问官网'
        ).then(action => {
            if (action === '检查更新') {
                vscode.commands.executeCommand('snakecasepro.checkUpdate');
            } else if (action === '查看公告') {
                vscode.commands.executeCommand('snakecasepro.showAnnouncement');
            } else if (action === '访问官网') {
                vscode.env.openExternal(vscode.Uri.parse('https://goodit.58it.cn'));
            }
        });
    });

    context.subscriptions.push(
        setApiKeyCommand,
        setAiModelCommand,
        clearApiKeyCommand,
        checkUpdateCommand,
        showAnnouncementCommand,
        showAboutCommand,
        openSettingsCommand,
        showConfigCommand,
        camelCaseCommand,
        pascalCaseCommand,
        snakeCaseCommand,
        kebabCaseCommand
    );
}

export function deactivate() { } 